<?php
namespace Home\Controller;

use Think\Controller;

class CouponsController extends CommonController
{
  //商品分类
  protected $this_table="coupons";

  //TP构造函数,子类同时调用
  public function __construct()
  {
    parent::__construct();

    #TODO：查看权限需要进一步加强
  }

  public function _before_index()
  {
    $this->auth_validate('index', true);
  }

  public function _before_create()
  {
    $this->auth_validate('create', true);
  }

  public function _before_update()
  {
    $this->auth_validate('update', true);
  }

  public function _before_status()
  {
    $this->auth_validate('status', true);
  }

  public function _before_receive()
  {
    $this->auth_validate('receive');
  }

  public function _before_select()
  {
    $this->auth_validate('select');
  }

  public function _before_show()
  {
    $this->auth_validate('show');
  }

  /**
   * [增/删/改权限检查]
   * @return [type] [description]
   */
  private function auth_validate($action, $is_business = false)
  {
    $this->check_login();

    //是否商户用户
    if (empty($this->shop_id) && $this->types != 1 && $is_business) {
      return_data("error", "$action.{$this->this_table}.deny", $this->shop_id);
    }
  }

  /**
   * 商户优惠券信息
   * @return [type] [description]
   */
  public function index()
  {
    $model = M($this->this_table);
    $status = trim(I('status'));
    $where = ' shop_id='.$this->shop_id;
    if ($status) {
      $where .= ' and status='.$status  ;
    }
    $fields = "*";
    $list = $model->field($field)->where($where)->order("id asc")->select();

    if ($list) {
      foreach ($list as $key => $value) {
        $list[$key]['activated_at'] = format_datetime($list[$key]['activated_at']);
        $list[$key]['expired_at'] = format_datetime($list[$key]['expired_at']);
      }

      return_data("success", "index.".$this->this_table.".success", $list);
    } else {
      return_data("error", "index.".$this->this_table.".empty");
    }
  }

  public function show()
  {
    $id = trim(I('id'));
    $result = M('coupons')->alias('c')
      ->field('c.*, s.logo shop_logo, s.name shop_name')
      ->join("left join shops s on s.id=c.shop_id")
      ->where("c.id=$id")->find();

    if ($result) {
      $result['activated_at'] = format_datetime($result['activated_at']);
      $result['expired_at'] = format_datetime($result['expired_at']);

      return_data('success', 'coupon.show.success', $result);
    } else {
      return_data('error', 'coupon.show.error');
    }
  }

  public function create()
  {
    $model = M($this->this_table);

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    unset($data['id']);
    unset($data['status']);
    unset($data['shop_id']);
    $default_data = array(
      'shop_id' => $this->shop_id,
      'created_at' => $this->current_time,
      'updated_at' => $this->current_time);
    $data = array_merge($default_data, $data);

    //参数判断
    if (!$data['name']) {
      return_data("error", $this->this_table.".name.blank");
    }
    if (!$data['total_num']) {
      return_data("error", $this->this_table.".total_num.blank");
    }
    if (!$data['activated_at']) {
      return_data("error", $this->this_table.".activated_at.blank");
    }
    if (!$data['expired_at']) {
      return_data("error", $this->this_table.".expired_at.blank");
    }
    if (!$data['amount']) {
      return_data("error", $this->this_table.".amount.blank");
    }

    $model->create($data);
    $id = $model->add();
    if (empty($id)) {
      return_data("error", "create.".$this->this_table.".error");//blank
    } else {
      return_data("success", "create.".$this->this_table.".success", $id);
    }
  }

  /**
   * [修改优惠券]
   * @return [type] [description]
   */
  public function update()
  {
    $model = M($this->this_table);

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    $data['updated_at'] = $this->current_time;

    $map = array(
      'id' => $data['id'],
      'shop_id' => $this->shop_id);
    $coupon = $model->where($map)->find();
    if (!$coupon) {
      return_data("error", $this->this_table.".id.error");
    }

    //只有未开始的优惠券可以修改
    if ($coupon['status']!=1) {
      return_data("error", $this->this_table.".status.invalid");
    }

    unset($data['status']);
    unset($data['shop_id']);
    unset($data['created_at']);

    $model->create($data);
    $result = $model->where($map)->save($data);

    if ($result) {
      $coupon = $model->where($map)->find();
      //如果生效时间已到，更新成发行中
      if ($coupon['activated_at'] < date("Y-m-d H:i:s", $this->current_time)) {
        $model->where($map)->save(array('status' => 2));
      }
      return_data("success", "update.".$this->this_table.".success");
    } else {
      return_data("error", "update.".$this->this_table.".error");
    }
  }

  /**
   * [优惠券状态操作]
   * status 1:未开始；2：进行中；3：失效
   * @return [type] [description]
   */
  public function status()
  {
    $model = M($this->this_table);

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    $map = array(
      'id' => $data['id'],
      'shop_id' => $this->shop_id);
    $coupon = $model->where($map)->find();
    if (!$coupon) {
      return_data("error", $this->this_table.".id.error");
    }

    //只能从1转为2或者2转为3
    $status_arr = array(2, 3);
    if ($data['status']-$coupon['status']!=1) {
      return_data("error", $this->this_table.".status.error");
    }

    $data['updated_at'] = $this->current_time;
    $result = $model->where($map)->save($data);

    if ($result) {
      return_data("success", "{$this->this_table}.status.success");
    } else {
      return_data("error", "{$this->this_table}.status.error");
    }
  }

  /**
   * [用户领取优惠券]
   * @return [type] [description]
   */
  public function receive()
  {
    $model = M('user_coupons');

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    $coupon =  M($this->this_table)->where("id={$data['coupon_id']}")->find();
    //参数判断
    if (!$coupon) {
      return_data("error", "receive.coupon_id.error");
    }

    if ($coupon['status'] != 2) {
      return_data("error", "receive.coupon.status.invalid");
    }
    if ($coupon['provided_num'] >= $coupon['total_num']) {
      return_data("error", "receive.coupon.provided_num.full");
    }

    $data = array(
      'user_id' => $this->user_id,
      'created_at' =>  $this->current_time,
      'updated_at' =>  $this->current_time,
      'coupon_id' => $data['coupon_id']);

    $model->create($data);
    $id = $model->add();
    if (empty($id)) {
      return_data("error", "receive.coupon.error");//blank
    } else {
      M($this->this_table)->where("id={$coupon['id']}")->save(array('provided_num'=>$coupon['provided_num']+1));
      return_data("success", "receive.coupon.success", $id);
    }
  }

  /**
   * [选择优惠券]
   * @return [type] [description]
   */
  public function select()
  {
    $model = M('user_coupons');

    $shop_id = trim(I('shop_id'));
    if (!$shop_id) {
      return_data("error", "select.shop_id.empty");
    }
    $map=array(
      'c.shop_id' => $shop_id,
      'c.status' => 2,
      'uc.user_id' => $this->user_id,
      'uc.status' => 1,
      "c.expired_at >= CURRENT_TIMESTAMP",
      "c.activated_at <= CURRENT_TIMESTAMP"
    );

    $order = "c.amount desc,c.expired_at asc ";
    $field = "uc.id,c.name,c.amount,c.expired_at";
    $list = M('user_coupons')->alias("uc")
          ->join("left join ".C('DB_PREFIX')."coupons c on uc.coupon_id=c.id")
          ->field($field)->where($map)->order($order)->select();

    return_data("success", "select.coupons.success", $list);
  }
}
